<template>
  <div>
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <select-confirm-batch
          placeholder="审核批次"
          @change="getData()"
          @clear="getData()"
          clearable
          v-model="params['apply_batch_no.eq']"
        ></select-confirm-batch>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="通过时间(开始)"
          end-placeholder="通过时间(截止)"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData"></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <!-- <confirm-sign-attach-dialog :visible.sync="signAttachVisible"
                                :batch-data="signAttachBatchData"></confirm-sign-attach-dialog> -->

    <attach-upload-dialog
      :visible.sync="signAttachVisible"
      :attach-id="signAttachBatchNo"
      :before-upload="beforeUpload"
      attach-tag="项目确认表"
      title="盖章上传"
      @success="onUploadSuccess"
    ></attach-upload-dialog>

    <confirm-view-dialog
      :visible.sync="viewVisible"
      :batch-data="viewBatchData"
    ></confirm-view-dialog>

    <confirm-attach-dialog
      :visible.sync="attachVisible"
      :batch-data="attachBatchData"
    ></confirm-attach-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumConfirmStatus,
  enumConfirmStatusStyle,
  enumWarrantyStatus,
  enumWarrantyStyle,
} from '@/bank/views/limit/confirm/mixins'
import { lastPickerShortcuts } from '@/common/plugins/tools/date'
import { deleteOss } from '@/common/api/oss'

import SelectConfirmBatch from '@/bank/views/business/limit/history/confirm/SelectConfirmBatch'
import ConfirmViewDialog from '@/bank/views/business/limit/history/confirm/ConfirmViewDialog'
import ConfirmAttachDialog from '@/bank/views/business/limit/history/confirm/ConfirmAttachDialog'
// import ConfirmSignAttachDialog from '@/bank/views/limit/confirm/ConfirmSignAttachDialog'
import AttachUploadDialog from '@/bank/components/attach/UploadDialog'

export default {
  components: {
    SelectConfirmBatch,
    ConfirmViewDialog,
    ConfirmAttachDialog,
    // ConfirmSignAttachDialog
    AttachUploadDialog,
  },
  props: {},
  data() {
    return {
      enumConfirmStatus,

      loading: false,
      params: {
        index: 1,
        size: 10,
        'apply_batch_no.eq': '',
        'is_confirm.eq': '0',
        'channel_type.eq': 0,
        'is_rural_dev.eq': 0,
        'project_count_approval.gt': 0,
      },
      order: {
        approval_time: 'desc',
      },
      tableName: 'project_approval_batch_bank',
      tableColumns: [
        { attrs: { label: '审核批次', prop: 'apply_batch_no', align: 'center' } },
        { attrs: { label: '审核数量', prop: 'project_count', align: 'center' } },
        { attrs: { label: '审核总额(万元)', prop: 'project_funds', align: 'center' } },
        {
          attrs: { label: '审核机构', prop: 'person', align: 'center' },
          process: () => '省农担',
        },
        {
          attrs: { label: '通过时间', prop: 'approval_time', align: 'center' },
          process: v => (v || '').substring(0, 10),
        },
        { attrs: { label: '通过数量', prop: 'project_count_approval', align: 'center' } },
        { attrs: { label: '通过金额(万元)', prop: 'project_funds_approval', align: 'center' } },
        { attrs: { label: '应收担保费(元)', prop: 'warranty_fee', align: 'center' } },
        {
          attrs: { label: '担保费收取', prop: 'warrantyStatus', align: 'center' },
          process: (_, row) => ({ attrs: { class: `text-${row.warrantyStyle}` } }),
        },
        {
          attrs: { label: '批次状态', prop: 'confirmStatusLabel', align: 'center' },
          process: (_, row) => ({ attrs: { class: `text-${row.confirmStatusStyle}` } }),
        },
        {
          attrs: { label: '操作', align: 'center', minWidth: '200px' },
          operations: [
            {
              name: '盖章上传',
              event: this.handleSignAttach,
              ifRender: row => row.is_confirm === 0,
            },
            { name: '附件', event: this.handleView },
            { name: '查看', event: this.handleAttach },
          ],
        },
      ],
      tableData: [],
      tableCount: 0,

      // 提交时间选择
      datePicked: [],
      pickerOptions: {
        shortcuts: lastPickerShortcuts,
      },

      // 查看
      viewVisible: false,
      viewBatchData: {},

      // 附件上传
      attachVisible: false,
      attachBatchData: {},

      // 盖章上传
      signAttachVisible: false,
      signAttachBatchData: {},
      signAttachBatchNo: '',
    }
  },
  computed: {
    ...mapGetters(['clientId', 'userId']),
    productId() {
      return this.$route.query.id
    },
  },
  watch: {},
  created() {
    this.params['submit_person.eq'] = this.userId
    this.getData()
  },
  mounted() {},
  methods: {
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = (res && res.data) || {}
          this.tableData = (data.data || []).map(this.dataAdapter)
          this.tableCount = data.totalCount || 0
        })
        .finally(() => {
          this.loading = false
        })
    },

    dataAdapter(item) {
      item.is_confirm = +(item.is_confirm || 0)
      item.confirmStatusLabel = enumConfirmStatus[item.is_confirm]
      item.confirmStatusStyle = enumConfirmStatusStyle[item.is_confirm]
      item.warrantyStatus = enumWarrantyStatus[item.warranty_fee_confirm]
      item.warrantyStyle = enumWarrantyStyle[item.warranty_fee_confirm]
      return item
    },

    handleDateChange() {
      const [start, end] = this.datePicked || []
      if (start && end) {
        this.params['approval_time.gte'] = start
        this.params['approval_time.lte'] = `${end} 23:59:59`
      } else {
        this.params['approval_time.gte'] = ''
        this.params['approval_time.lte'] = ''
      }
      this.getData()
    },

    handleSignAttach(row = {}) {
      this.signAttachBatchData = row
      this.signAttachBatchNo = row.project_approval_batch_bank_id
      this.signAttachVisible = true
    },

    handleView(row = {}) {
      this.viewBatchData = row
      this.viewVisible = true
    },

    handleAttach(row = {}) {
      this.attachBatchData = row
      this.attachVisible = true
    },

    beforeUpload() {
      return new Promise((resolve, reject) => {
        this.$utils
          .msgbox({
            message: '确定盖章上传（上传后该审核批次将变成已确认）？',
            type: 'warning',
          })
          .then(() => {
            resolve(true)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    handleSuccess() {
      this.getData()
      this.$store.dispatch('getTaskCountLimit', { type: 0, id: this.productId })
    },
    onUploadSuccess(res) {
      this.loading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.signAttachBatchNo, {
          is_confirm: 1,
        })
        .then(() => {
          this.$message.success('盖章上传成功！')
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error('盖章上传失败!')

          // 错误后，要删除附件信息和oss文件
          const { list = [] } = res || {}
          this.deleteAttachByBatchNo(list)

          throw new Error(err)
        })
        .finally(() => {
          this.loading = true
        })
    },

    deleteAttachByBatchNo(list) {
      this.$api
        .deleteDataBody(this.$serviceName, 'datum_customer_attachment', {
          customer_related_id: this.signAttachBatchNo,
        })
        .then(() => {
          deleteOss(list)
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
